package com.jie.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jie.dao.AllCatDao;
import com.jie.entity.Cat;
import com.jie.entity.QuerInfo;
import com.jie.service.CatService;
import com.jie.utility.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jie
 * @since 2023-12-18
 */
@RestController
@RequestMapping("/rear-end/cat")
public class CatController {
    @Autowired
    private CatService catService;

    /**
     * 添加分类
     * @param cat
     * @return
     */

    @PostMapping("/addCat")
    public R<String> addCat(@RequestBody Cat cat){
        boolean save = catService.save(cat);
        if(save){
            return R.success("添加成功");
        }
        return R.error("添加分类失败");
    }

    /**
     * 查询所以分类
     * @param
     * @return
     */
    @GetMapping("/categories")
    public R<List<AllCatDao>> allcat(Integer pagenum,Integer pagesize,Integer type){
        QuerInfo queryInfo = new QuerInfo();
        if(pagenum!=null){
            queryInfo.setPagenum(pagenum);
        }
        if(pagesize!=null){
            queryInfo.setPagesize(pagesize);
        }
        if(type!=null){
            queryInfo.setType(type);
        }

           if(pagenum==null && pagesize==null&&type!=null){
               return R.success(catService.parentcat(queryInfo.getType()));
           }
        if(pagenum==null && pagesize==null&&type==null){
            return R.success(catService.allcat());
        }
            Page<AllCatDao> page = catService.allcat(queryInfo);
            List<AllCatDao> allCatDaos=new ArrayList<>();
            for (Object record : page.getRecords()) {
                AllCatDao allCatDao = JSON.parseObject(JSON.toJSONString(record), AllCatDao.class);
                allCatDaos.add(allCatDao);
            }
            Map<String, Integer> map=new HashMap<>();
            map.put("total", (int) page.getTotal());
            return R.success(allCatDaos,map);
    }

    /**
     * 修改分类
     * @param cat
     * @return
     */
    @PostMapping("/updateCat")
    public R<String> updateCat(@RequestBody Cat cat){
        boolean b = catService.updateById(cat);
        if(b){
        return  R.success("修改分类成功！");
        }
       return R.error("修改分类失败！");
    }

    /**
     * 删除分类
     * @param catId
     * @return
     */
    @GetMapping("/delCat")
    public R<String> delCat(String catId){
        boolean save = catService.removeById(catId);
        if(save){
            return R.success("删除分类成功");
        }
         return  R.error("删除分类失败");
    }
}

